package com.alinesno.cloud.operation.cmdb.third.wechat.controller.handler;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alinesno.cloud.operation.cmdb.common.constants.ParamsEnum;
import com.alinesno.cloud.operation.cmdb.common.constants.RunerEnum;
import com.alinesno.cloud.operation.cmdb.common.util.EmojiFilter;
import com.alinesno.cloud.operation.cmdb.entity.ParamsEntity;
import com.alinesno.cloud.operation.cmdb.entity.UserEntity;
import com.alinesno.cloud.operation.cmdb.repository.UserRepository;
import com.alinesno.cloud.operation.cmdb.service.ParamsService;
import com.alinesno.cloud.operation.cmdb.third.wechat.WechatService;
import com.alinesno.cloud.operation.cmdb.third.wechat.controller.WechatMessageBase;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutTextMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 微信消息
 * 
 * @author LuoAnDong
 * @since 2018年10月11日 上午8:58:53
 */
@Component("wechat_message_event")
public class WechatMessageEventHandler extends WechatMessageBase {

	private static final Logger logger = LoggerFactory.getLogger(WechatMessageEventHandler.class);

	private static final String SUBSCRIBE = "subscribe"; // 订阅事件
	private static final String UNSUBSCRIBE = "unsubscribe"; // 取消订阅事件

	@Autowired
	private ParamsService paramsService;

	@Autowired
	private WechatService wechatService;

	@Autowired
	private UserRepository userRepository;

	@Override
	public Object handlerMessage(WxMpXmlMessage message, String fromUser, String toUser, String event, String content) {

		if (SUBSCRIBE.equals(event)) {

			ParamsEntity param = paramsService.findParamByName(ParamsEnum.WECHAT_SUBSCRIBE.getCode(), null);
			WxMpXmlOutTextMessage text = WxMpXmlOutTextMessage.TEXT().toUser(fromUser).fromUser(toUser)
					.content(param != null ? param.getParamValue() : "欢迎关注").build();

			// 获取用户基础信息
			try {
				UserEntity user = userRepository.findByOpenId(fromUser);
				
				if (user == null) {
					WxMpUser wxUser = wechatService.userInfo(fromUser);
					
					String filterNickName = EmojiFilter.filterNickName(wxUser.getNickname()) ; 
					wxUser.setNickname(filterNickName) ; 
					
					logger.debug("获取微信用户{}, nickname :{} , 过滤nickname :{}结果:{}" , fromUser, wxUser.getNickname() , filterNickName , wxUser);
					
					user = new UserEntity();
					user.setAddTime(new Date()); //注册时间 
					user.setFieldProp(RunerEnum.STATUS_MEMBER.getCode());
					BeanUtils.copyProperties(wxUser, user);
					
					userRepository.save(user);
				}
			} catch (WxErrorException e) {
				logger.error("获取用户{}信息失败:{}", message.getOpenId(), e);
			}

			return text.toXml();
		} else if (UNSUBSCRIBE.equals(event)) {

		}

		return null;
	}

}
